import { batchUpdateOrgApi, getUserServiceObjectListApi, queryOrgTreeApi } from '@/api/sys/organization'
import { qualificationTypeAllApi } from '@/api/sys/qualificationType'
import { queryRoleTreeApi } from '@/api/sys/roleManage'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { requestWithTry } from '@/utils/request'

const BatchEditModal = ({ selectedRow = [] }) => {
  const [form] = AekForm.useForm()

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'departmentId',
      label: '组织架构',
      component: {
        name: 'AekTreeSelect',
        props: {
          api: queryOrgTreeApi,
          fieldNames: { value: 'departmentId', label: 'departmentName' },
        },
      },
    },
    {
      field: 'roleIds',
      label: '角色',
      component: {
        name: 'AekTreeSelect',
        props: {
          api: queryRoleTreeApi,
          fieldNames: { value: 'roleId', label: 'roleName' },
          treeCheckable: true,
        },
      },
    },
    {
      field: 'serviceObjectList',
      label: '擅长内容',
      component: {
        name: 'AekTreeSelect',
        props: {
          api: getUserServiceObjectListApi,
          fieldNames: { value: 'serviceObjectId', label: 'serviceObjectName', children: 'childList' },
          treeCheckable: true,
        },
      },
    },
    {
      field: 'qualificationTypeList',
      label: '资质类型',
      component: {
        name: 'AekSelect',
        props: {
          api: qualificationTypeAllApi,
          fieldNames: { value: 'id', label: 'qualificationTypeName' },
          mode: 'multiple',
        },
      },
    },
    {
      field: 'qualificationFileList',
      label: '资质证书',
      formItemProps: {
        help: '支持扩展名：.png .jpg .jpeg .bmp .pdf .doc .docx',
      },
      component: {
        name: 'AekUpload',
        props: { fileType: 'unset' },
      },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      ...values,
      userIds: selectedRow.map(({ id }) => id),
      serviceObjectList: values.serviceObjectList?.map(id => ({ serviceObjectId: id, source: 0 })),
      qualificationTypeList: values.qualificationTypeList?.map(id => ({ id })),
      qualificationFileList: values.qualificationFileList?.map(({ url }) => url),
    }
    await requestWithTry(batchUpdateOrgApi, params)
  }
  return (
    <AekModal title='批量更改' width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

BatchEditModal.PromiseThen = PromiseThen

export default BatchEditModal
